package com.yumaolin.deepunderstand.leetcode.algorithm.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 114.前序遍历的非递归实现
 * 1.先将根节点入栈
 * 2.出栈顶元素，add到链表。
 * 3.将栈顶元素的左右子树的根节点入栈（为空时，就没必要入栈）。入栈的时候，先入右树，再入左树，
 * 这样就可以在出栈的时候先出左后出右
 */
public class PreOrderTraversal {

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> sortList = new ArrayList<>();
        if (root == null) {
            return sortList;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.empty()) {
            TreeNode top = stack.pop();
            sortList.add(top.val);
            if (top.right != null) {
                stack.push(top.right);
            }
            if (top.left != null) {
                stack.push(top.left);
            }
        }
        return sortList;
    }


    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
